package com.caucho.hessian.serializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;

public class ThrowableSerializer extends AbstractSerializer {
    @Override
    public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
        if (obj != null) {
            final Class cl = obj.getClass();
            if (out.addRef(obj))
                return;
            int ref = out.writeObjectBegin(cl.getName());
            Throwable tr = (Throwable) obj;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            try {
                oos.writeObject(tr);
                if (ref < -1) {
                    out.writeString("value");
                    out.writeBytes(bos.toByteArray());
                    out.writeMapEnd();
                } else {
                    if (ref == -1) {
                        out.writeInt(1);
                        out.writeString("value");
                        out.writeObjectBegin(cl.getName());
                    }
                    out.writeBytes(bos.toByteArray());
                }
            } finally {
                oos.close();
                bos.close();
            }
        } else
            out.writeNull();
    }
}